package org.PropertyManageMentSystem.Manager;

import org.PropertyManageMentSystem.Data.Comment;
import org.PropertyManageMentSystem.Data.MysqlConfig;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CommentManager {
    private Connection conn;

    public CommentManager(MysqlConfig config) {
        String url = config.getUrl();
        String user = config.getUser();
        String password = config.getPassword();

        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            //创建连接
            this.conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void addComment(Long taskId, int timelinessScore, int attitudeScore, int satisfiedScore, String info) {
        try {
            String sql = "Insert into comment (taskId, timelinessScore, attitudeScore, satisfiedScore, info) values(?, ?, ?, ?, ?)";
            PreparedStatement stat = conn.prepareStatement(sql);//SQL语句已预编译并存储在PreparedStatement对象中。


            //setString(int parameterIndex, String x) 将指定的参数设置为给定的Java String值
            stat.setLong(1, taskId); //即将p.getName()所获得值赋给第1个问号的地方

            stat.setInt(2, timelinessScore);//同理将getPrice()所获得的值赋给第2个问号地方
            stat.setInt(3, attitudeScore);
            stat.setInt(4, satisfiedScore);
            stat.setString(5, info);

            //执行sql语句
            stat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public ArrayList<Comment> getCommentByTaskId(Long taskId) {
        ArrayList<Comment> comments = new ArrayList<Comment>();
        try {
            String sql = "select * from comment where taskId=?";
            PreparedStatement stat = conn.prepareStatement(sql);

            stat.setLong(1, taskId);
            //因为executeQuery会有ResultSet的返回值
            ResultSet res = stat.executeQuery();

            //将res中的值取出给到集合里面
            while (res.next()) {
                Long commentId = res.getLong("commentId");
                Integer timelinessScore = res.getInt("timelinessScore");
                Integer attitudeScore = res.getInt("attitudeScore");
                Integer satisfiedScore = res.getInt("satisfiedScore");
                String info = res.getString("info");
                Comment comm = new Comment(commentId,taskId, timelinessScore, attitudeScore, satisfiedScore, info);
                //添加到容器
                comments.add(comm);
            }
            return comments;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
